package com.java110.mall.cart.storeOrderEngine;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.product.ProductDto;
import com.java110.dto.product.ProductGroupDto;
import com.java110.dto.product.ProductGroupOrderDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderReturnPayDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.goods.IProductGroupOrderV1InnerServiceSMO;
import com.java110.intf.goods.IProductGroupV1InnerServiceSMO;
import com.java110.intf.goods.IProductInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.mall.cart.bmo.storeOrder.IUpdateStoreOrderBMO;
import com.java110.po.product.ProductGroupOrderPo;
import com.java110.po.storeOrder.StoreOrderPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.ListUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
public class StoreGroupOrderEngine {

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IProductGroupOrderV1InnerServiceSMO productGroupOrderV1InnerServiceSMOImpl;

    @Autowired
    private IProductGroupV1InnerServiceSMO productGroupV1InnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Autowired
    private StoreOrderEngine storeOrderEngine;

    @Autowired
    private IUpdateStoreOrderBMO updateStoreOrderBMOImpl;


    public ResultVo unifiedOrder(JSONObject reqJson) {
        String userId = reqJson.getString("user-id");// cmdDataFlowContext.getReqHeaders().get("user-id");
        String appId = reqJson.getString("app-id");// cmdDataFlowContext.getReqHeaders().get("app-id");
        reqJson.put("appId", appId);

        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "用户不存在");

        ProductDto productDto = new ProductDto();
        productDto.setShopId(reqJson.getString("shopId"));
        productDto.setProductId(reqJson.getString("productId"));
        productDto.setValueId(reqJson.getString("valueId"));
        productDto.setGroupId(reqJson.getString("groupId"));
        List<ProductDto> productDtos = productInnerServiceSMOImpl.queryGroupProducts(productDto);

        if (ListUtil.isNull(productDtos)) {
            throw new IllegalArgumentException("未包含商品");
        }

        ProductGroupOrderDto productGroupOrderDto = new ProductGroupOrderDto();
        productGroupOrderDto.setGroupId(reqJson.getString("groupId"));
        productGroupOrderDto.setState(ProductGroupOrderDto.STATE_W);
        productGroupOrderDto.setPage(1);
        productGroupOrderDto.setRow(Integer.parseInt(productDtos.get(0).getUserCount()));
        List<ProductGroupOrderDto> productGroupOrderDtos = productGroupOrderV1InnerServiceSMOImpl.queryProductGroupOrders(productGroupOrderDto);

        String groupBuyerId = userDtos.get(0).getUserId();
        String groupBuyerName = userDtos.get(0).getName();
        String buyerId = userDtos.get(0).getUserId();
        String buyerName = userDtos.get(0).getName();
        String openGrouper = ProductGroupOrderDto.OPEN_GROUPER_Y;
        String sessionId = GenerateCodeFactory.getGeneratorId("11");
        if (!ListUtil.isNull(productGroupOrderDtos)
                && productGroupOrderDtos.size() < Integer.parseInt(productDtos.get(0).getUserCount())) {
            groupBuyerId = productGroupOrderDtos.get(0).getGroupBuyerId();
            groupBuyerName = productGroupOrderDtos.get(0).getGroupBuyerName();
            openGrouper = ProductGroupOrderDto.OPEN_GROUPER_N;
            sessionId = productGroupOrderDtos.get(0).getSessionId();
        }

        ProductGroupOrderPo productGroupOrderPo = new ProductGroupOrderPo();
        productGroupOrderPo.setGroupBuyerId(groupBuyerId);
        productGroupOrderPo.setOrderId(reqJson.getString("orderId"));
        productGroupOrderPo.setRebateAmount("0");
        productGroupOrderPo.setGroupId(reqJson.getString("groupId"));
        productGroupOrderPo.setBuyerCount(reqJson.getString("goodsNum"));
        productGroupOrderPo.setBuyerId(buyerId);
        productGroupOrderPo.setBuyerName(buyerName);
        BigDecimal groupPrice = new BigDecimal(Double.parseDouble(reqJson.getString("goodsNum")));
        groupPrice = groupPrice.multiply(new BigDecimal(Double.parseDouble(productDtos.get(0).getGroupPrice()))).setScale(2, BigDecimal.ROUND_HALF_UP);
        productGroupOrderPo.setGroupPrice(groupPrice.doubleValue() + "");
        productGroupOrderPo.setProdName(productDtos.get(0).getProdName());
        productGroupOrderPo.setGroupBuyerName(groupBuyerName);
        productGroupOrderPo.setShopId(productDtos.get(0).getShopId());
        productGroupOrderPo.setState(ProductGroupOrderDto.STATE_W);
        productGroupOrderPo.setAddressId(reqJson.getString("addressId"));
        productGroupOrderPo.setRemark(reqJson.getString("remark"));
        productGroupOrderPo.setGroupCount("1");
        productGroupOrderPo.setOpenGrouper(openGrouper);
        productGroupOrderPo.setSessionId(sessionId);


        int flag = productGroupOrderV1InnerServiceSMOImpl.saveProductGroupOrder(productGroupOrderPo);

        if (flag < 1) {
            throw new CmdException("下单失败");
        }

        productGroupOrderDto = new ProductGroupOrderDto();
        productGroupOrderDto.setGroupId(reqJson.getString("groupId"));
        productGroupOrderDto.setState(ProductGroupOrderDto.STATE_W);
        productGroupOrderDto.setPage(1);
        productGroupOrderDto.setRow(Integer.parseInt(productDtos.get(0).getUserCount()));
        productGroupOrderDto.setSessionId(sessionId);
        productGroupOrderDtos = productGroupOrderV1InnerServiceSMOImpl.queryProductGroupOrders(productGroupOrderDto);

        ProductGroupOrderPo tmpProductGroupOrderPo = new ProductGroupOrderPo();
        tmpProductGroupOrderPo.setGroupId(reqJson.getString("groupId"));
        tmpProductGroupOrderPo.setGroupBuyerId(productGroupOrderDtos.get(0).getGroupBuyerId());
        tmpProductGroupOrderPo.setGroupCount(productGroupOrderDtos.size() + "");
        tmpProductGroupOrderPo.setState(ProductGroupOrderDto.STATE_W);
        tmpProductGroupOrderPo.setSessionId(sessionId);
        flag = productGroupOrderV1InnerServiceSMOImpl.updateProductGroupOrder(tmpProductGroupOrderPo);
        if (flag < 1) {
            throw new CmdException("下单失败");
        }

        if (productGroupOrderDtos.size() >= Integer.parseInt(productDtos.get(0).getUserCount())) {
            //生成订单
            for (ProductGroupOrderDto tmpProductGroupOrderDto : productGroupOrderDtos) {
                doUnifiedOrder(tmpProductGroupOrderDto, appId);
            }
        }
        return new ResultVo(ResultVo.CODE_OK, ResultVo.MSG_OK);
    }

    /**
     * {"storeOrder":
     * {"remark":"",
     * "personId":"302022101738360013",
     * "personName":"test001",
     * "userId":"302022101738360013"},
     * "storeOrderCarts":[{"cateType":"1","productId":"902022120101840004",
     * "prodName":"香蕉","valueId":"912022120139430012",
     * "goodsNum":1,"shopId":"502022081626050001",
     * "cartType":"3306"}],
     * <p>
     * "shopId":"502022081626050001",
     * "addressId":"822022120277730346",
     * "tradeType":"JSAPI"}
     *
     * @param productGroupOrderDto
     */
    private void doUnifiedOrder(ProductGroupOrderDto productGroupOrderDto, String appId) {

        JSONObject orderInfo = new JSONObject();
        orderInfo.put("shopId", productGroupOrderDto.getShopId());
        orderInfo.put("addressId", productGroupOrderDto.getAddressId());
        orderInfo.put("appId", appId);

        JSONObject storeOrder = new JSONObject();
        storeOrder.put("personId", productGroupOrderDto.getBuyerId());
        storeOrder.put("personName", productGroupOrderDto.getBuyerName());
        storeOrder.put("userId", productGroupOrderDto.getBuyerId());
        storeOrder.put("remark", productGroupOrderDto.getRemark());
        orderInfo.put("storeOrder", storeOrder);

        JSONArray storeOrderCarts = new JSONArray();

        ProductGroupDto productGroupDto = new ProductGroupDto();
        productGroupDto.setGroupId(productGroupOrderDto.getGroupId());
        List<ProductGroupDto> productGroupDtos = productGroupV1InnerServiceSMOImpl.queryProductGroups(productGroupDto);

        Assert.listOnlyOne(productGroupDtos, "商品不存在");

        JSONObject storeOrderCart = new JSONObject();
        storeOrderCart.put("cateType", "1");
        storeOrderCart.put("productId", productGroupDtos.get(0).getProductId());
        storeOrderCart.put("prodName", productGroupDtos.get(0).getProdName());
        storeOrderCart.put("valueId", productGroupDtos.get(0).getValueId());
        storeOrderCart.put("goodsNum", productGroupOrderDto.getBuyerCount());
        storeOrderCart.put("shopId", productGroupOrderDto.getShopId());
        storeOrderCart.put("business", StoreOrderDto.BUSINESS_GROUP);
        storeOrderCart.put("groupId",productGroupOrderDto.getGroupId());

        storeOrderCart.put("cartType", "3306");
        storeOrderCarts.add(storeOrderCart);
        orderInfo.put("storeOrderCarts", storeOrderCarts);
        StoreOrderReturnPayDto storeOrderReturnPayDto = storeOrderEngine.unifiedOrder(orderInfo);

        StoreOrderPo storeOrderPo = new StoreOrderPo();
        storeOrderPo.setOrderId(storeOrderReturnPayDto.getOrderId());
        updateStoreOrderBMOImpl.update(storeOrderPo);

        ProductGroupOrderPo productGroupOrderPo = new ProductGroupOrderPo();
        productGroupOrderPo.setOrderId(productGroupOrderDto.getOrderId());
        productGroupOrderPo.setState(ProductGroupOrderDto.STATE_C);
        productGroupOrderPo.setCartId(storeOrderReturnPayDto.getOrderId());
        int flag = productGroupOrderV1InnerServiceSMOImpl.updateProductGroupOrder(productGroupOrderPo);
        if (flag < 1) {
            throw new CmdException("下单失败");
        }

    }
}
